package com.ns.dcjh.utils;

import android.util.Base64;

import com.bytedance.sdk.open.aweme.utils.Md5Utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelperUtils {
    private static final Pattern linePattern = Pattern.compile("_(\\w)");
    private static final Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, Objects.requireNonNull(matcher.group(1)).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 字符串转base64
     * @param str
     * @return
     */
    public static String strToBase64(String str) {
        return Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
    }

    /**
     * 获取随机字符
     * @param length
     * @return string
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int num = random.nextInt(str.length());
            sb.append(str.charAt(num));
        }
        return sb.toString();
    }

    public static String createSignature(ArrayList<String> signArr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < signArr.size(); i++) {
            sb.append(signArr.get(i));
            sb.append("-");
        }
        String signStr = sb.toString();
        signStr = signStr.substring(0, signStr.length() - 1).toLowerCase();
        signStr = Md5Utils.hexDigest(signStr);
        if (StringUtils.isNotEmpty(signStr)) {
            signStr = signStr.substring(2, 26).toLowerCase();
        }

        return signStr;
    }
}
